﻿using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid;
using Fluid.Ast;

namespace ZYing.LiquidThemeEngine.Ast
{
    public class RenderStatement : Statement
    {
        public RenderStatement(Expression pathExpression, Expression with, IList<AssignStatement> assignStatements)
        {
            PathExpression = pathExpression;
            With = with;
            AssignStatements = assignStatements;
        }

        public Expression PathExpression { get; }

        public IList<AssignStatement> AssignStatements { get; }

        public Expression With { get; }

        public override async ValueTask<Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext ctx)
        {
            var context = (LiquidThemeTemplateContext)ctx;
            context.IncrementSteps();
            var name = (await PathExpression.EvaluateAsync(context)).ToStringValue();
            var path = Helper.CombinePath(Constants.Directories.Snippets, Helper.NormalTemplateFile(name));
            var partialTemplate = await context.GetTemplateAsync(path);
            try
            {
                context.EnterChildScope();
                if (With != null)
                {
                    var identifier = Helper.NormalTemplateName(name);
                    var with = await With.EvaluateAsync(context);
                    context.SetValue(identifier, with);
                }

                if (AssignStatements != null)
                {
                    foreach (var assignStatement in AssignStatements)
                    {
                        await assignStatement.WriteToAsync(writer, encoder, context);
                    }
                }
                await partialTemplate.RenderAsync(writer, encoder, context);
            }
            finally
            {
                context.ReleaseScope();
            }

            return Completion.Normal;
        }
    }
}